/**
 * FileName: PayController
 * Author:   afei
 * Date:     2018/11/10 19:28
 * Description: 支付模块
 */
package com.stylefeng.guns.rest.modular.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.rest.common.persistence.model.MoviePayApplyRecord;
import com.stylefeng.guns.rest.common.persistence.model.MoviePayRecords;
import com.stylefeng.guns.rest.common.persistence.model.MovieVip;
import com.stylefeng.guns.rest.common.persistence.model.PayRequestVO;
import com.stylefeng.guns.rest.modular.applications.service.IMovieService;
import com.stylefeng.guns.rest.modular.auth.util.JsonParseObjectUtil;
import com.stylefeng.guns.rest.modular.auth.util.MD5Utils;
import com.stylefeng.guns.rest.modular.auth.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈支付模块〉
 *
 * @author afei
 * @create 2018/11/10
 * @since 1.0.0
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    //第三方服务器地址
    public final static String IP_ADDRESS = "http://43.254.219.98:8001";
    //商户id(商户号，接⼊后由第三方支付提供)
    public final static String appid = "4789";
    //第三方支付的key
    public static final String key ="834607fc284346dd9c5fd13ea66fc01b";

    //服务器ip地址
    public final static String SERVICE_ADDRESS = "http://47.254.22.186:8082";
    //⽀付提交接⼝
    public final static String PAY_ADDRESS = "/sdkServer/thirdpays/pay";
    //代付提交接⼝
    public final static String DRAW_ADDRESS = "/sdkServer/thirdpays/draw";
    //代付查询接⼝
    public final static String DRAWQUERY_ADDRESS = "/sdkServer/thirdpays/drawquery";
    //异步回调函数的地址
    public final static String NOTIFYURL_ADDRESS = "/pay/payNotifyUrl";

    @Autowired
    private IMovieService movieService;

    //提交支付
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/submitPay", method = RequestMethod.POST)
    public Object submitPay(PayRequestVO vo) {
        try {
            MovieVip movieVip = movieService.selectByParams(vo.getVipType());
            if (!vo.getMoney().equals(movieVip.getPrice())) {
                return ResponseEntity.ok(ResultUtil.error("开通会员类型与金额不符合"));
            }
            //唯一值，用作定交互记录单号
            long time = System.currentTimeMillis();
            String transp = vo.getAccountId() + String.valueOf(time);
            //交易金额（单位：分）
            String money = vo.getMoney();
            //签名
            String sign = MD5Utils.submitPaySign(appid,money,transp,key);
            String service = "wappay";
            String notifyUrl = SERVICE_ADDRESS + NOTIFYURL_ADDRESS;
            //String notifyUrl = "http://myURL/notifytest/order_001";
            //同步回调地址 非必填
            String callbackUrl = "";
            //支付方式
            String payMethod = vo.getPayMethod();
            String url = IP_ADDRESS + PAY_ADDRESS;
            String postParam = "service=" + service + "&payMethod=" + payMethod + "&appid="
                    + appid + "&transp=" + transp + "&money=" + money + "&sign=" + sign + "&notifyUrl=" + notifyUrl + "&callbackUrl=" + callbackUrl;

            JSONObject result = JsonParseObjectUtil.postMethod(url, postParam);
            if (null != result && result.getIntValue("errcode") == 0) {
                JSONObject obj = result.getJSONObject("result");
                //添加一个支付提交申请记录
                MoviePayApplyRecord moviePayApplyRecord = new MoviePayApplyRecord();
                moviePayApplyRecord.setAccountId(vo.getAccountId());
                moviePayApplyRecord.setOrderid(transp);
                moviePayApplyRecord.setPaymethod(payMethod);
                moviePayApplyRecord.setPrice(money);
                moviePayApplyRecord.setVipType(vo.getVipType());
                movieService.insertSelective(moviePayApplyRecord);
                return ResponseEntity.ok(ResultUtil.success(obj));
            } else {
                return ResponseEntity.ok(ResultUtil.error("提交支付请求失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ResultUtil.error(e.getMessage()));
        }
    }

    //⽀付完成后的异步通知返回
    @RequestMapping(value = "/payNotifyUrl")
    @ResponseBody
    public String payNotifyUrl(MoviePayRecords moviePayRecords) {
        //判断成功返回状态
        if ("success".equals(moviePayRecords.getStatus())) {
            movieService.insertSelective(moviePayRecords);
            //更新会员vip状态和会员到期时间
            movieService.updateVipStatus(moviePayRecords);
            return "success";
        } else {
            return "支付未成功";
        }
    }


    //支付查询记录
    @RequestMapping(value = "/payApplyRecord")
    @ResponseBody
    public Object payApplyRecord(String accountId) {
        try {
            List<MoviePayApplyRecord> moviePayApplyRecords = movieService.payApplyRecord(accountId);
            return ResponseEntity.ok(ResultUtil.success(moviePayApplyRecords));
        } catch (Exception e) {
            return ResponseEntity.ok(ResultUtil.error(e.getMessage()));
        }
    }

}